//
//  MyInformationViewController.m
//  lsOA
//
//  Created by 蓝水软件 on 16/7/18.
//  Copyright © 2016年 苏州蓝水有限公司. All rights reserved.
//

#import "MyInformationViewController.h"
#import "MyInformationTableViewCell.h"
#import "MyMessageViewController.h"
#import "MeetViewController.h"

#import "WorkTaskViewController.h"
#import "DocReviewViewController.h"
#import "AddressBookViewController.h"
#import "ScreenUiView.h"
#import "UserFollowViewController.h"
#import "NoNetWorkingView.h"

@interface MyInformationViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate>{
    NSMutableDictionary *mutableDic;
    UILabel *allNum;
    UISearchController *searchVC;
    NSMutableArray *searchArray;
   
    ScreenUiView *screen;   //筛选控件
    NoNetWorkingView *netWorkView;   //断网控件
    
    UIButton *nullButton;    //数据空 点击重新加载
    UILabel *nullLabel;      //label 数据空空如也
    //加载失败
    //    UIButton *tryAgain;
    //    UILabel *faile;
    //    UILabel *faile2;
    
}


@property (nonatomic,strong) UIButton *tryAgain;
@property (nonatomic,strong) UILabel *faile;
@property (nonatomic,strong)UILabel *faile2;


@property (nonatomic,strong) YALSunnyRefreshControl *sunnyRefreshControl;
@end

@implementation MyInformationViewController

- (void)viewWillDisappear:(BOOL)animated{
    //让搜索控件消失
    [searchVC setActive:NO];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"noNetWork" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
}
- (void)viewWillAppear:(BOOL)animated{
    
    [self beginAnimationHandle3];
    //注册管擦者，接受网络状态观察者发送过来的关于网络的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNoNetWorkTag:) name:@"noNetWork" object:nil];
}

/**
 *  获取表格数据
 */
- (void)getData:(NSDictionary *)dic{
    self.model = [[FileListModel alloc]init];
    [GMDCircleLoader setOnView:self.view withTitle:@"" animated:YES];
    [_model getData:self.fromView listType:self.listType screenDic:dic];
    __block MyInformationViewController *blockSelf = self;
    self.model.block = ^(BOOL success){
        if (success) {
            [blockSelf.screenButton setHidden:NO];
            [blockSelf.table reloadData];
            [blockSelf setValue];
            [blockSelf hidenButton:YES];
        }else{
            [blockSelf.screenButton setHidden:YES];
            [blockSelf hidenButton:NO];
        }
        [blockSelf endAnimationHandle];
        [GMDCircleLoader hideFromView:blockSelf.view animated:YES];
    };
}
//在请求成功再将失败时的控件隐藏，防止后来联网又刷新到数据
- (void)hidenButton:(BOOL)hidden{
    _tryAgain.hidden = hidden;
    _faile.hidden = hidden;
    _faile2.hidden = hidden;
    self.table.hidden = !hidden;
}

/**
 *  绘制界面
 */
- (void)setUI{
    _table = [[UITableView alloc]init];
    _table.delegate = self;
    _table.dataSource = self;
    _table.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_table];
    _table.frame = CGRectMake(0, 0, KSWidth, KSHeight-90);
    allNum = [[UILabel alloc]init];
    [self.view addSubview:allNum];
    [allNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_table.mas_bottom).offset(2);
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(KSWidth);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    allNum.font = [UIFont systemFontOfSize:10];
    [self setupRefreshControl];
    searchVC = [[UISearchController alloc]initWithSearchResultsController:nil];
    searchVC.searchResultsUpdater = self;
    searchVC.searchBar.delegate = self;
    searchVC.dimsBackgroundDuringPresentation = NO;
    searchVC.hidesNavigationBarDuringPresentation = NO;
    
    if ([self.fromView intValue] == 5) {
        searchVC.searchBar.frame = CGRectMake(searchVC.searchBar.frame.origin.x, searchVC.searchBar.frame.origin.y, searchVC.searchBar.frame.size.width, 45*FitSize);
        _table.tableHeaderView = searchVC.searchBar;
    }else{
        UIBarButtonItem *screenBarButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(doScreen)];
        self.navigationItem.rightBarButtonItem = screenBarButton;
    }
    
    /**
     *  这些界面默认是不显示
     */
    _tryAgain = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_tryAgain];
    [_tryAgain setImage:[UIImage imageNamed:@"失败再次提交l"] forState:UIControlStateNormal];
    [_tryAgain mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(150, 150));
    }];
    _tryAgain.hidden = YES;
    [_tryAgain addTarget:self action:@selector(loadAgain) forControlEvents:UIControlEventTouchUpInside];
    
    _faile = [[UILabel alloc]init];
    [self.view addSubview:_faile];
    _faile.text = @"啊咧，似乎出了点问题...";
    _faile.hidden = YES;
    _faile.textAlignment = NSTextAlignmentCenter;
    _faile.textColor = [UIColor lightGrayColor];
    [_faile mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tryAgain.mas_bottom).offset(5);
        make.width.mas_equalTo(KSWidth);
        make.centerX.equalTo(self.view);
    }];
    
    _faile2 = [[UILabel alloc]init];
    [self.view addSubview:_faile2];
    _faile2.text = @"点击重新加载";
    _faile2.hidden = YES;
    _faile2.textAlignment = NSTextAlignmentCenter;
    _faile2.textColor = [UIColor colorWithRed:0.788 green:0.074 blue:0.202 alpha:1.000];
    [_faile2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_faile.mas_bottom).offset(5);
        make.width.mas_equalTo(KSWidth);
        make.centerX.equalTo(self.view);
    }];
    
    //数据为空时显示
    nullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [nullButton setImage:[UIImage imageNamed:@"空数据l"] forState:UIControlStateNormal];
    [self.view addSubview:nullButton];
    nullButton.hidden = YES;
    [nullButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(150, 150));
    }];
    
    [nullButton addTarget:self action:@selector(sunnyControlDidStartAnimation) forControlEvents:UIControlEventTouchUpInside];
    nullLabel = [[UILabel alloc]init];
    nullLabel.text = @"数据空空如也~~";
    [self.view addSubview:nullLabel];
    nullLabel.textAlignment = NSTextAlignmentCenter;
    nullLabel.hidden = YES;
    nullLabel.textColor = [UIColor lightGrayColor];
    [nullLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nullButton.mas_bottom).offset(10);
        make.width.mas_equalTo(KSWidth);
    }];

    
   

   
}
//根据网络状态观察者传来的值进行判断，如果为－1就显示控件
- (void)showNoNetWorkTag:(NSNotification *)sender{
    NSString *isConnection = [sender object];
    if ([isConnection isEqualToString:@"-1"]) {
        netWorkView = [[NoNetWorkingView alloc]initWithFrame:CGRectMake(0, 0, KSWidth, 35)];
        _table.tableHeaderView = netWorkView;
    }else{
        //有网络，隐藏控件，并重新发送请求数据
        _table.tableHeaderView = nil;
        [self sunnyControlDidStartAnimation];
    }
}


//重新加载界面显示
- (void)loadAgain{
    [self sunnyControlDidStartAnimation];
    [_tryAgain setHidden:YES];
    [_faile setHidden:YES];
    [_faile2 setHidden:YES];
}

//筛选按钮响应事件
- (void)doScreen{
    screen = [[ScreenUiView alloc]initWithFromView:self.fromView];
    screen.frame = self.view.bounds;
    [self.view addSubview:screen];
    __weak MyInformationViewController *blockSelf = self;
    screen.block = ^(NSDictionary *dic){
        [blockSelf.model getData:blockSelf.fromView listType:blockSelf.listType screenDic:dic];
    };
}


/**
 *  设置数据
 */
- (void)setValue{
    NSArray *array = self.model.dataArray;
    if (array.count == 0) {
        _table.hidden = YES;
        nullLabel.hidden = NO;
        nullButton.hidden = NO;
       
    
    }else{
        nullLabel.hidden = YES;
        nullButton.hidden = YES;
        
    }
    allNum.text = [NSString stringWithFormat:@"当前总计－ %d 条  记录数据  ",array.count];
}

# pragma mark - YALSunyRefreshControl methods

-(void)setupRefreshControl{
    self.sunnyRefreshControl = [YALSunnyRefreshControl new];
    [self.sunnyRefreshControl addTarget:self
                                 action:@selector(sunnyControlDidStartAnimation)
                       forControlEvents:UIControlEventValueChanged];
    [self.sunnyRefreshControl attachToScrollView:_table];
}


//刷新执行事件 其实他应该算重新加载数据
-(void)sunnyControlDidStartAnimation{
    NSDictionary *dic = @{@"conditions":@"",@"starTime":@"",@"endTime":@"",@"verify":@"100"};
    [self getData:dic];
}

- (void)beginAnimationHandle3{
    [self.sunnyRefreshControl beginRefreshing];
    
}

-(void)endAnimationHandle{
    
    [self.sunnyRefreshControl endRefreshing];
}
/**
 *  推送界面 － 响应表格点击事件
 *
 *  @param fromView 用于区别从哪个界面点击过来的
 *  @param type     用于区别界面具体详情的类型
 *  @param detailDic     详情界面需要显示的数据
 */
- (void)pushView:(NSString *)fromView  listType:(NSString *)type NSDic:(NSDictionary *)detailDic {
    
    switch ([fromView intValue]) {
        case 1:{
            MyMessageViewController *myMessage = [[MyMessageViewController alloc]init];
            myMessage.type = type;
            myMessage.dic = detailDic;
            [self.navigationController pushViewController:myMessage animated:YES];
        }
            break;
        case 2:{
            MeetViewController *meet = [[MeetViewController alloc]init];
            meet.type = type;
            meet.dic = detailDic;
            [self.navigationController pushViewController:meet animated:YES];
        }
            break;
        case 3:{
            DocReviewViewController *docReview = [[DocReviewViewController alloc]init];
            docReview.type = type;
            docReview.dic = detailDic;
            [self.navigationController pushViewController:docReview animated:YES];
        }
            break;
        case 4:{
            WorkTaskViewController *workTask = [[WorkTaskViewController alloc]init];
            
            workTask.dic = detailDic;
            [self.navigationController pushViewController:workTask animated:YES];
        }
            break;
        case 5:{
            AddressBookViewController *addressBook = [[AddressBookViewController alloc]init];
            addressBook.type = type;
            addressBook.dic = detailDic;
            [self.navigationController pushViewController:addressBook animated:YES];
            

        }
            break;
            
        default:{
            
        }
            break;
    }
}

/**
 *  表格行点击事件
 *  这是跳转到内容详情 首先判读是资讯还是会议等  再判断是资讯中的具体分类
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //网络请求到的字典
    NSDictionary *detailData = self.model.dataArray[indexPath.row];
    [self pushView:self.fromView listType:self.listType NSDic:detailData ];
}
/**
 *  表格行数
 *
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array = self.model.dataArray;
    return array.count;
}
/**
 *  每行高度
 *
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70*FitSize;
}

/**
 *
 *  表格每行格式
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellID = @"CellID";
    MyInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (!cell) {
        cell = [[MyInformationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    NSDictionary *dic = self.model.dataArray[indexPath.row];
    NSLog(@"%@",dic);
    [cell setValueWithDic:dic withFromView:self.fromView listType:self.listType];
    
    
    
    
    return cell;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString = searchVC.searchBar.text;
    if (searchArray != nil) {
        [searchArray removeAllObjects];
    }
    NSDictionary *dic = @{@"conditions":searchString};
    [self getData:dic];
    [_table reloadData];
}




@end
